use std::fmt::{Display, Formatter};
use serde::Serialize;
use actix_web::{error, HttpResponse};
use actix_web::http::StatusCode;
use sqlx::error::Error as SQLXError;

#[derive(Debug,Serialize)]
pub enum MyError{
    DBError(String),
    ActixError(String),
    NotFound(String),
}

#[derive(Debug,Serialize)]
pub struct MyErrorResponse{
    error_message: String
}

impl MyError{
    fn error_response(&self) -> String{
        match self {
            MyError::DBError(msg) => {
                println!("DB Error: {:?}", msg);
                "Database Error".into()
            }
            MyError::ActixError(msg) => {
                println!("Actix Error: {:?}", msg);
                "Internal Server Error".into()
            }
            MyError::NotFound(msg) => {
                println!("NotFound: {:?}", msg);
                msg.into()
            }
        }
    }
}

impl Display for MyError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self)
    }
}

impl error::ResponseError for MyError{
    fn status_code(&self) -> StatusCode {
        match self {
            MyError::DBError(msg) | MyError::ActixError(msg) => StatusCode::INTERNAL_SERVER_ERROR,
            MyError::NotFound(msg) => StatusCode::NOT_FOUND,
        }
    }
    fn error_response(&self) -> HttpResponse {
        HttpResponse::build(self.status_code()).json(MyErrorResponse{
            error_message: self.to_string()
        })
    }
}

impl From<actix_web::error::Error> for MyError {
    fn from(error: actix_web::error::Error) -> Self {
        MyError::ActixError(error.to_string())
    }
}

impl From<SQLXError> for MyError {
    fn from(error: SQLXError) -> Self {
        MyError::DBError(error.to_string())
    }
}
